package com.itheima.springbootwebtlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.anno.LogOperation;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.pojo.ClaQueryParam;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    //添加班级
    @LogOperation
    @Override
    public void saveClazz(Clazz clazz) {
        log.info("保存班级信息：{}", clazz);
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.saveClazz(clazz);
    }

    //查询全部班级信息
    @Override
    public List<Clazz> findAll() {
        List<Clazz> clazzList = clazzMapper.findAll();
        log.info("查询全部班级信息：{}", clazzList);
        return clazzList;
    }

    //条件+分页查询
    @Override
    public PageResult page(ClaQueryParam claQueryParam) {
        //1.分页插件
        log.info("分页查询，参数：{}", claQueryParam);
        PageHelper.startPage(claQueryParam.getPage(), claQueryParam.getPageSize());
        //2.执行查询
        Page<Clazz> page = (Page<Clazz>) clazzMapper.selectByCondition(claQueryParam);
        //3.调用分页插件的增强持久层方法
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

        return pageResult;
    }

    //删除班级,需要异常处理
    @LogOperation
    @Override
    public void delClazz(Integer id) {
        //查询当前班级是否已结课
        // 如果未结课，则不允许删除,定义查询当前班级的状态方法
        Integer counts = clazzMapper.selectCountsById(id);
        if (counts!=0) {
            throw new DeletionIsNotAllowed("对不起, 该班级下有学生, 不能直接删除");
        } else {
            log.info("删除班级，id：{}", id);
            clazzMapper.delClazz(id);
        }

    }

    //编辑班级信息，查询班级信息+回显
    @Override
    public Clazz findById(Integer id) {
        //1.查询班级信息
        Clazz clazz = clazzMapper.findById(id);
        //2.返回班级信息
        return clazz;
    }

    //修改班级,编辑功能
    @LogOperation
    @Override
    public void update(Clazz clazz) {
        //调用Mapper层修改班级信息
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
}
